package com.cocostudio.erpapp;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.loader.app.LoaderManager;
import androidx.loader.app.LoaderManager.LoaderCallbacks;
import androidx.loader.content.AsyncTaskLoader;
import androidx.loader.content.Loader;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.cocostudio.erpapp.provider.Settings;
import com.cocostudio.erpapp.utils.StringUtil;
import com.cocostudio.erpapp.utils.WebServiceUtils;
import com.cocostudio.erpapp.vo.LoginResult;
import com.cocostudio.erpapp.vo.RegistionResult;
import com.cocostudio.erpapp.vo.WSLoginResult;
import com.cocostudio.erpapp.web.Apis;
import com.cocostudio.erpapp.web.Keys;
import com.cocostudio.erpapp.web.ServerRequester;
import com.cocostudio.erpapp.web.ServerRequester.Parameters;
import com.cocostudio.erpapp.web.ServerRequester.Result;

public class RegLoginActivity extends CustomFragmentActivity {
    
    private static String TAG="RegLoginActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.activity_reg_login);
        
        setTitle(R.string.title_login);
        setLeftButtonDrawable(R.drawable.btn_back);
        
        FragmentManager fm = getSupportFragmentManager();
        fm.beginTransaction().add(R.id.content, new LoginFragment()).commit();
    }

    @Override
    protected boolean onLeftButtonClicked() {
        return getSupportFragmentManager().popBackStackImmediate();
    }

    public static class LoginFragment extends Fragment implements LoaderCallbacks<LoginResult> {

        private EditText uid;
        private EditText password;
        private ProgressDialog pdg;
        private SharedPreferences localstore;
        
        private Spinner server_config_spinner;

        
        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            ((RegLoginActivity) getActivity()).setTitle(R.string.title_login);
                  }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            
            final View view = inflater.inflate(R.layout.fragment_login, null);
            
            localstore =getActivity(). getSharedPreferences(WebServiceUtils.LOCALSTORE, Context.MODE_PRIVATE);

            
            String local_uid = localstore.getString("userid", "");
            String local_pwd = localstore.getString("password","");

            uid = (EditText) view.findViewById(R.id.username);
            password = (EditText) view.findViewById(R.id.password);
            
            initServerConfigUI(view);
            
            //uid.setText("00318");
           // password.setText("2014484");
            
            uid.setText(local_uid);
            password.setText(local_pwd);
            
            view.findViewById(R.id.configserver).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    getFragmentManager()
                    .beginTransaction()
                    .replace(R.id.content, new ConfigFragment())
                    .addToBackStack("configserver").commit();
                }
            });
              
            view.findViewById(R.id.login).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                    try {
                        pdg = ProgressDialog.show(v.getContext(), "温馨提示", "数据请求中，请稍后！");
                        pdg.setCancelable(true);
                        pdg.setCanceledOnTouchOutside(true);
                        String s_uid = uid.getText().toString();
                        String s_pwd = password.getText().toString();
                        WSLoginResult result = WebServiceUtils.WS_Login( s_uid, s_pwd);
                        if (result != null) {
                            if (result.getResult() == 1) {
                                result.setPersonCode(s_uid);
                                MainActivity.curlogin = result; 
                                Toast.makeText(v.getContext(), "登录成功", Toast.LENGTH_LONG).show();
                               
                                WebServiceUtils.setDeptResult(result);
                                
                                
                                //保存用户名密码
                                Editor editor = localstore.edit();
                                editor.putString("userid", s_uid);
                                editor.putString("password",  s_pwd );
                                editor.commit();
                                Log.d("SavePassword", "uid:"+s_uid+" password:"+s_pwd);
                                startActivity(new Intent(getActivity(), MainActivity.class));
                            } else {
                                Toast.makeText(v.getContext(), "登录失败:" + result.getMessage(), Toast.LENGTH_LONG).show();
                            }
                        } else {
                            Toast.makeText(v.getContext(), "登录失败", Toast.LENGTH_LONG).show();
                        }
                        
                        pdg.dismiss();

                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }  
                    
                    /*
                     * LoaderManager loaderManager = getLoaderManager();
                     * Loader<Object> loader = loaderManager.getLoader(0); if
                     * (loader == null) { loaderManager.initLoader(0, null,
                     * LoginFragment.this); } else { loader.forceLoad();
                     * LoadingFragment.show(getFragmentManager(),
                     * (AsyncTaskLoader<?>) loader); }
                     */
                }

            });
            return view;
        }

        private String getUrlByServerName(String name)
        {
            String rtn="";
            String s1 =   localstore.getString("server1","");
            String s2 =   localstore.getString("server2","");
            String s3 =  localstore.getString("server3","");
            
            if ( s1.equals( name))
                return localstore.getString("url1","");
            if (s2.equals( name))
                return localstore.getString("url2","");
            if (s3.equals( name))
                return localstore.getString("url3","");
            
            
            return rtn;
        }
        private String[] getServerList(){
            ArrayList<String> list = new ArrayList<String>();
            
            String s1 =   localstore.getString("server1","");
            String s2 =   localstore.getString("server2","");
            String s3 =  localstore.getString("server3","");
            if ( !s1.trim().equals("") )
                list.add(s1);
            if ( !s2.trim().equals("") )
                list.add(s2);
            if ( !s3.trim().equals("") )
                list.add(s3);
            
            String[] rtnlist =new String[list.size()];
            list.toArray(rtnlist);
            return rtnlist;
        }
        private void initServerConfigUI(final View view) {
            
            
            server_config_spinner = (Spinner)view.findViewById(R.id.search_server_spinner);
            server_config_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    
                    String item = (String)server_config_spinner.getItemAtPosition(position);
                    WebServiceUtils.SERVER_URL = getUrlByServerName(item)+"/WebServer.asmx";

                }
                @Override
                public void onNothingSelected(AdapterView<?> parent){
                    Log.d(RegLoginActivity.TAG, "select onNothing");
                }
            });
           
            
            ArrayAdapter<String> _Adapter_showtype=new ArrayAdapter<String>( getActivity(),android.R.layout.simple_dropdown_item_1line, getServerList());
            server_config_spinner.setAdapter(_Adapter_showtype);
        }

        @Override
        public Loader<LoginResult> onCreateLoader(int id, Bundle args) {
            AsyncTaskLoader<LoginResult> loader = new AsyncTaskLoader<LoginResult>(getActivity()) {
                @Override
                public LoginResult loadInBackground() {
                    Parameters params = new Parameters(null);
                    params.put(Keys.UID, uid.getText().toString());
                    params.put(Keys.PW, password.getText().toString());
                    Result result = ServerRequester.requestByGet(Apis.API_LOGIN, params);
                    return result.isOk() ? (LoginResult) result.vo : null;
                }

                @Override
                protected void onStartLoading() {
                    forceLoad();
                }

                @Override
                protected void onStopLoading() {
                    cancelLoad();
                }
            };
            LoadingFragment.show(getFragmentManager(), loader);
            return loader;
        }

        @Override
        public void onLoadFinished(Loader<LoginResult> loader, LoginResult data) {
            LoadingFragment.dismiss(getFragmentManager(), new Handler());
            if (data != null) {
                if (data.status > 0) {
                    Toast.makeText(getActivity(), getString(R.string.msg_welcome, data.uid), Toast.LENGTH_SHORT).show();
                    Settings.saveUID(getActivity(), data.uid);
                    getActivity().setResult(RESULT_OK);
                    getActivity().finish();
                } else {
                    Toast.makeText(getActivity(), data.msg, Toast.LENGTH_LONG).show();
                }
            } else {
                Toast.makeText(getActivity(), R.string.msg_login_failed, Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onLoaderReset(Loader<LoginResult> loader) {
        }
    }

    public static class ConfigFragment extends Fragment {
        
        private EditText server_1;
        private EditText url_1;
    
        private EditText server_2;
        private EditText url_2;
        
        private EditText server_3;
        private EditText url_3;
        
        private SharedPreferences localstore;

        
        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            ((RegLoginActivity) getActivity()).setTitle("后台服务器配置");
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            final View view = inflater.inflate(R.layout.fragment_serverconfig, null);
            
            
            localstore =getActivity(). getSharedPreferences( WebServiceUtils.LOCALSTORE, Context.MODE_PRIVATE);

            
            
            
            server_1 = (EditText) view.findViewById(R.id.config_server_name_1);
            url_1 = (EditText) view.findViewById(R.id.config_server_url_1);
            
            server_2 = (EditText) view.findViewById(R.id.config_server_name_2);
            url_2 = (EditText) view.findViewById(R.id.config_server_url_2);
            
            server_3 = (EditText) view.findViewById(R.id.config_server_name_3);
            url_3= (EditText) view.findViewById(R.id.config_server_url_3);
            
            
            if (  localstore.getString("server1","").equals("")){
                server_1.setText("默认服务器");
                url_1.setText("http://erp.uvhc.cn" );
            }
            else{
                server_1.setText(  localstore.getString("server1","").toString());
                url_1.setText( localstore.getString("url1","").toString());
            }
            
            server_2.setText(  localstore.getString("server2","").toString());
            url_2.setText( localstore.getString("url2","").toString());
            
            server_3.setText(  localstore.getString("server3","").toString());
            url_3.setText( localstore.getString("url3","").toString());
            
            view.findViewById(R.id.confirm_server_config).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                   
                    Editor editor = localstore.edit();
                    editor.putString("server1", server_1.getText().toString());
                    editor.putString("url1",  url_1.getText().toString() );
                    
                    editor.putString("server2", server_2.getText().toString());
                    editor.putString("url2",  url_2.getText().toString() );
                    
                    editor.putString("server3", server_3.getText().toString());
                    editor.putString("url3",  url_3.getText().toString() );
                    
                    editor.commit();
                    
                    Toast.makeText(getActivity(), "保存完毕！", Toast.LENGTH_LONG).show();
                   
                    getFragmentManager().popBackStack();
                    
                  
                }
            });
            return view;
        }

       

        
    
        
    }
    
    @SuppressLint("HandlerLeak")
    public static class RegisterFragment extends Fragment implements LoaderCallbacks<RegistionResult> {

        private EditText uid;
        private EditText password;
        private EditText repassword;
        private EditText email;
        private EditText mobile;
        private EditText company;

        private Handler mHandler = new Handler() {
            @Override
            public void handleMessage(android.os.Message msg) {
                getFragmentManager().popBackStack();
            }
        };

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            ((RegLoginActivity) getActivity()).setTitle(R.string.title_reg);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            final View view = inflater.inflate(R.layout.fragment_register, null);
            uid = (EditText) view.findViewById(R.id.username);
            password = (EditText) view.findViewById(R.id.password);
            repassword = (EditText) view.findViewById(R.id.confirm_password);
            email = (EditText) view.findViewById(R.id.email);
            mobile = (EditText) view.findViewById(R.id.phone);
            company = (EditText) view.findViewById(R.id.company);
            view.findViewById(R.id.register).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (TextUtils.isEmpty(uid.getText())) {
                        Toast.makeText(getActivity(), R.string.msg_empty_username, Toast.LENGTH_LONG).show();
                        uid.requestFocus();
                        return;
                    }
                    if (TextUtils.isEmpty(password.getText())) {
                        Toast.makeText(getActivity(), R.string.msg_empty_password, Toast.LENGTH_LONG).show();
                        password.requestFocus();
                        return;
                    }
                    if (TextUtils.isEmpty(repassword.getText())) {
                        Toast.makeText(getActivity(), R.string.msg_empty_repassword, Toast.LENGTH_LONG).show();
                        repassword.requestFocus();
                        return;
                    }
                    if (TextUtils.isEmpty(email.getText())) {
                        Toast.makeText(getActivity(), R.string.msg_empty_email, Toast.LENGTH_LONG).show();
                        email.requestFocus();
                        return;
                    }
                    if (!StringUtil.isEmail(email.getText().toString())) {
                        Toast.makeText(getActivity(), R.string.msg_wrong_email, Toast.LENGTH_LONG).show();
                        email.requestFocus();
                        return;
                    }
                    if (TextUtils.isEmpty(mobile.getText())) {
                        Toast.makeText(getActivity(), R.string.msg_empty_phone, Toast.LENGTH_LONG).show();
                        mobile.requestFocus();
                        return;
                    }
                    if (!StringUtil.isMobileNO(mobile.getText().toString())) {
                        Toast.makeText(getActivity(), R.string.msg_wrong_phone, Toast.LENGTH_LONG).show();
                        mobile.requestFocus();
                        return;
                    }
                    if (TextUtils.isEmpty(company.getText())) {
                        Toast.makeText(getActivity(), R.string.msg_empty_company, Toast.LENGTH_LONG).show();
                        company.requestFocus();
                        return;
                    }

                    if (password.getText().toString().trim().equals(repassword.getText().toString().trim())) {
                        LoadingFragment.show(getFragmentManager());
                        LoaderManager loaderManager = getLoaderManager();
                        Loader<Object> loader = loaderManager.getLoader(0);
                        if (loader == null) {
                            loaderManager.initLoader(0, null, RegisterFragment.this);
                        } else {
                            loader.forceLoad();
                        }
                    } else {
                        Toast.makeText(getActivity(), R.string.msg_wrong_repassword, Toast.LENGTH_LONG).show();
                    }
                }
            });
            return view;
        }

        @Override
        public Loader<RegistionResult> onCreateLoader(int id, Bundle args) {
            AsyncTaskLoader<RegistionResult> loader = new AsyncTaskLoader<RegistionResult>(getActivity()) {
                @Override
                public RegistionResult loadInBackground() {
                    Parameters params = new Parameters(null);
                    params.put(Keys.UID, uid.getText().toString().trim());
                    params.put(Keys.PW, password.getText().toString().trim());
                    params.put(Keys.EMAIL, email.getText().toString().trim());
                    params.put(Keys.MOBILE, mobile.getText().toString().trim());
                    params.put(Keys.COMPANY, company.getText().toString().trim());
                    Result result = ServerRequester.requestByGet(Apis.API_REGISTER, params);
                    return result.isOk() ? (RegistionResult) result.vo : null;
                }

                @Override
                protected void onStartLoading() {
                    forceLoad();
                }

                @Override
                protected void onStopLoading() {
                    cancelLoad();
                }
            };
            return loader;
        }

        @Override
        public void onLoadFinished(Loader<RegistionResult> loader, RegistionResult data) {
            LoadingFragment.dismiss(getFragmentManager(), new Handler());
            if (data != null) {
                if (data.status > 0) {
                    Toast.makeText(getActivity(), getString(R.string.msg_register_success, data.uid), Toast.LENGTH_SHORT).show();
                    mHandler.obtainMessage().sendToTarget();
                } else {
                    Toast.makeText(getActivity(), data.msg, Toast.LENGTH_LONG).show();
                }
            } else {
                Toast.makeText(getActivity(), R.string.msg_regsiter_failed, Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onLoaderReset(Loader<RegistionResult> loader) {
        }
    }
}
